package com.smsc.headend.task.engine.service.firmware.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.SystemClock;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.smsc.headend.common.constant.DeviceModel;
import com.smsc.headend.common.enums.DeviceType;
import com.smsc.headend.common.enums.errorcode.TaskExecuteErrorCode;
import com.smsc.headend.module.asset.dmo.ComConfigDMO;
import com.smsc.headend.module.asset.entity.ComEntity;
import com.smsc.headend.module.fwu.entity.DeviceFirmwareVersion;
import com.smsc.headend.module.fwu.entity.FirmwareFile;
import com.smsc.headend.module.fwu.entity.LogFwUpgradeHis;
import com.smsc.headend.module.fwu.entity.TemplateFwUpgrade;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.mapper.FirmwareFileMapper;
import com.smsc.headend.task.engine.service.DeviceFirmwareVersionService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.firmware.FirmwareService;
import com.smsc.headend.task.engine.service.task.TaskService;
import com.smsc.headend.task.engine.utils.TaskParamUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class FirmwareServiceImpl implements FirmwareService {

    @Autowired
    FirmwareFileMapper firmwareFileMapper;

    @Autowired
    AssetService assetService;

    @Autowired
    FeignAssetManagementService assetManagementService;

    @Autowired
    TaskService taskService;

    @Autowired
    DeviceFirmwareVersionService deviceFirmwareVersionService;

    @Override
    public String getFirmwareIdentifier(Long fwFileId) {
        LambdaQueryWrapper wrapper = Wrappers.<FirmwareFile>lambdaQuery().eq(FirmwareFile::getFwFileId, fwFileId).select(FirmwareFile::getFwFileIdentifier);
        FirmwareFile firmwareFile = firmwareFileMapper.selectOne(wrapper);
        return firmwareFile == null ? null : firmwareFile.getFwFileIdentifier();
    }

    @Override
    public void saveFwuReport(Task task, AtomicTask atomicTask, Integer result, TemplateFwUpgrade.TaskType firmwareUpgradeTaskType, String errorDesc, Long tvStart) {
//        if (atomicTask.getGroupId().intValue() == OperationGroup.FirmwareImageTransfer.getId()) {
//            return;
//        }
        ComEntity comEntity = assetService.getComById(task.getComId());
        Long deviceType;
        Long deviceId;
        if (task.getMeterId() != null) {
            deviceType = DeviceType.METER.getId();
            deviceId = task.getMeterId();
        } else {
            deviceType = comEntity.getComDeviceType();
            deviceId = comEntity.getDeviceId();
        }

        Long taskId = Convert.toLong(TaskParamUtils.getParameterMap(task, atomicTask).get("taskId"));

        Long tvEnd = SystemClock.now() / 1000;
        Integer upgradeResult = result > 0 ? LogFwUpgradeHis.UpgradeResult.success.getCode() : LogFwUpgradeHis.UpgradeResult.failed.getCode();
        assetManagementService.saveFwuReport(deviceId, deviceType, null, taskId, firmwareUpgradeTaskType.getCode(), upgradeResult, tvStart, tvEnd, errorDesc);
    }

    @Override
    public boolean isRetryMessageType(String message) {
        return message.equalsIgnoreCase("build aa fail")
                || message.equals(TaskExecuteErrorCode.TASK_WAITING_CON_RESPONSE_OVERTIME.toString())
                || message.equals(TaskExecuteErrorCode.TASK_WAITING_CON_RESPONSE_OVERTIME.getErrorText());
    }

    @Override
    public void saveFirmwareVersion(String firmwareVersion, Long fwTypeId, Task task, String fwFileTypeVersion, ComConfigDMO comConfig) {
        String allFirmwareVersion = firmwareVersion;
        log.info("saveFirmwareInfo:{},{}, {}, meterId={}, comId={}", firmwareVersion, fwTypeId, fwFileTypeVersion, task.getMeterId(), task.getComId());
        if (StrUtil.isNotEmpty(fwFileTypeVersion)) {
            allFirmwareVersion = firmwareVersion;
        }
//        if (task.getMeterId() == null && fwFileTypeVersion == null) {
//            //Wisun DCU MasterModule 固件id 11，12 代表同一版本信息中包含两个固件的版本号 ， COM-MASTER(11)是倒数两位， COM-MASTER1(12) 倒数3，4位
//            comConfig = comConfig == null ? assetService.getComConfigById(task.getComId()) : comConfig;
//            if (comConfig != null && comConfig.getModelId() == DeviceModel.WFCT_960 && (fwTypeId.equals(11L) || fwTypeId.equals(12L))) {
//                String first11Version = StrUtil.sub(allFirmwareVersion, allFirmwareVersion.length() - 2, allFirmwareVersion.length());
//                String sec12Version = StrUtil.sub(allFirmwareVersion, allFirmwareVersion.length() - 4, allFirmwareVersion.length() - 2);
//                allFirmwareVersion = fwTypeId.equals(11L) ? first11Version : sec12Version;
//                log.info("saveFirmwareInfo:{},{}, {}.{}", firmwareVersion, fwTypeId, first11Version, sec12Version);
//                DeviceFirmwareVersion deviceFirmwareVersion = new DeviceFirmwareVersion();
//                deviceFirmwareVersion.setFwVersion(fwTypeId.equals(11L) ? sec12Version : first11Version);
//                deviceFirmwareVersion.setFwType(fwTypeId.equals(11L) ? 12L : 11L);
//                deviceFirmwareVersion.setDeviceId(taskService.getDeviceId(task));
//                deviceFirmwareVersion.setDeviceType(taskService.getDeviceType(task));
//                deviceFirmwareVersionService.saveFirmwareVersion(deviceFirmwareVersion);
//            }
//        }
        DeviceFirmwareVersion deviceFirmwareVersion = new DeviceFirmwareVersion();
        deviceFirmwareVersion.setFwVersion(allFirmwareVersion);
        deviceFirmwareVersion.setFwType(fwTypeId);
        deviceFirmwareVersion.setDeviceId(taskService.getDeviceId(task));
        deviceFirmwareVersion.setDeviceType(taskService.getDeviceType(task));
        deviceFirmwareVersionService.saveFirmwareVersion(deviceFirmwareVersion);
    }
}
